#!/usr/bin/env python

import urllib, shlex, subprocess
from elementtree.ElementTree import parse
from mako.template import Template

WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s'
WEATHER_NS	= 'http://xml.weather.yahoo.com/ns/rss/1.0'
ICONSET_PATH = './Flat/large_icons/'

def weather_for_zip(zip_code):
	url = WEATHER_URL % zip_code
	rss = parse(urllib.urlopen(url)).getroot()
	current_condition = rss.find('channel/item/{%s}condition' % WEATHER_NS)
	forecasts = []
	for element in rss.findall('channel/item/{%s}forecast' % WEATHER_NS):
		forecasts.append({
			'date': element.get('date'),
			'low': element.get('low'),
			'high': element.get('high'),
			'condition': element.get('text'),
		})
	return {
		'current_condition': current_condition.get('text'),
		'current_condition_code': current_condition.get('code'),
		'current_temp': current_condition.get('temp'),
		'todays_high': forecasts[0]['high'],
		'todays_low': forecasts[0]['low']
	}

def write_svg_for_weather(weather, template, filename):
	image_template = Template(filename=template)
	f = open(filename, 'w')
	f.write(image_template.render(weather=weather))
	f.close()

tulsa = weather_for_zip(74137)
write_svg_for_weather(tulsa, 'template.svg', 'weather.svg')
subprocess.check_call(['convert', 'weather.svg', 'weather.png'])
command_line = 'composite -geometry +60+20 %(path)s%(code)s.png weather.png weather.png' % \
			    {'path': ICONSET_PATH, 'code': tulsa['current_condition_code']}
subprocess.check_call(shlex.split(command_line))
command_line = 'convert weather.png -type GrayScale -depth 4 weather-grayscale.png'
subprocess.check_call(shlex.split(command_line))
subprocess.check_call(['convert', 'weather-grayscale.png', 'weather.cip'])